﻿using LCL.Caching;
using LCL.Config;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Remoting;
using System.Text;

namespace LCL.LData
{
    /// <summary>
    /// 数据库信息类实例工厂,利用反射动态创建对象。
    /// </summary>
    public class DbObject
    {
        private static LCache cache = LCache.Instance;

        #region 不同程序集反射
        private static object CreateObject(string path, string typeName)
        {
            object obj = cache.Get<object>(typeName);
            if (obj == null)
            {
                try
                {
                    obj = Assembly.Load(path).CreateInstance(typeName);
                    cache.Set(typeName, obj);
                }
                catch (System.Exception ex)
                {
                    string str = ex.Message;
                }
            }
            return obj;
        }
        public static IDbObject CreateDbObj(string dbTypename)
        {
            string TypeName = "LCL.DbObjects." + dbTypename + ".DbObject";
            object objType = CreateObject("LCL.DbObjects", TypeName);
            return (IDbObject)objType;
        }
        public static IDbScriptBuilder CreateScript(string dbTypename)
        {
            string TypeName = "LCL.DbObjects." + dbTypename + ".DbScriptBuilder";
            object objType = CreateObject("LCL.DbObjects", TypeName);
            return (IDbScriptBuilder)objType;
        }
        #endregion

        #region 当前程序集反射
        public static IDbObject GetDbModel(DbConfigInfo conf)
        {
            string _typeName = "LCL.DbObjects." + conf.DbType + ".DbObject";
            object objType = cache.Get<object>(_typeName);
            if (objType == null)
            {
                ObjectHandle handle = Activator.CreateInstance("LCL.Common", _typeName);
                var iDbObject = (IDbObject)handle.Unwrap();
                iDbObject.DbConfig = conf;
                cache.Set(_typeName, iDbObject);
                return (IDbObject)iDbObject;
            }
            return (IDbObject)objType;
        }
        public static IDbScriptBuilder GetDbScript(DbConfigInfo conf)
        {
            string _typeName = "LCL.DbObjects." + conf.DbType + ".DbScriptBuilder";
            object objType = cache.Get<object>(_typeName);
            if (objType == null)
            {
                ObjectHandle handle = Activator.CreateInstance("LCL.Common", _typeName);
                var iDbObject = (IDbScriptBuilder)handle.Unwrap();
                iDbObject.DbConfig = conf;
                cache.Set(_typeName, iDbObject);
                return (IDbScriptBuilder)iDbObject;
            }
            return (IDbScriptBuilder)objType;
        }
        #endregion
    }
}
